package contact

import (
	"git.mycaigou.com/gfyx/common/simplecopier"
	dto "git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/dto/business_opportunity"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/repository/bigdata"
	pb "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
	"strings"
)

type ContactService struct {
	contactRepo        ContactRepositoryIface
	bigDataServiceRepo bigdata.BigdataRepositoryIface
}

// NewContactService
// 创建构造函数
func NewContactService(
	contactRepo ContactRepositoryIface,
	bigDataServiceRepo bigdata.BigdataRepositoryIface,
) ContactServiceIface {
	return &ContactService{
		contactRepo:        contactRepo,
		bigDataServiceRepo: bigDataServiceRepo,
	}
}

func (s *ContactService) getWinBidContact(ctx *gin.Context, request *pb.ContactListRequest, resp *pb.ContactListResponse) map[string]interface{} {
	request.Company = s.distinctName(ctx, request.Company) //中标单位去重
	res := map[string]interface{}{}
	if request.ContactType == "single_developer" {
		dataMap, err := simplecopier.StructToMapByJsonTag(resp)
		if err != nil {
			stark.Logger.Error(ctx, "struct to map,err:", err)
		}
		res["list"] = dataMap["contact_list"]
		res["total"] = resp.ContactTotal
		return res
	} else {
		cooperationCompany := &pb.ContactListResponse{}
		var companyNameArr []string
		cooperationCompanyTotal := 0
		startNum := 1
		if request.ContactType == "developer_and_supplier" {
			startNum = 0
		}
		for k, company := range request.Company {
			if company.CompanyName != "" {
				//合作单位
				cooperationCompanyItem := &pb.CooperationCompanyList{
					CooperationCompanyName:    company.CompanyName,
					CooperationOrganizingCode: company.OrganizingCode,
				}
				//联系人列表
				contactList := make([]*pb.ContactDataList, 0)
				for _, respValue := range resp.ContactList {
					if respValue.CompanyName == company.CompanyName {
						contactList = append(contactList, respValue)
						cooperationCompanyItem.ContactCnt += 1
					}
				}
				if len(contactList) > 2 {
					cooperationCompanyItem.Contact = contactList[0:2]
				} else {
					cooperationCompanyItem.Contact = contactList
				}
				//公司类型
				if k == 0 && request.ContactType == "developer_and_supplier" {
					cooperationCompanyItem.CompanyType = "developer"
				} else {
					cooperationCompanyItem.CompanyType = "supplier"
				}
				//联系人数量
				companyNameArr = append(companyNameArr, company.CompanyName)
				companyContactCntList := s.getCompanyTargetCnt(ctx, companyNameArr)
				for _, cnt := range companyContactCntList {
					if company.CompanyName == cnt.DeveloperName {
						if cooperationCompanyItem.CompanyType == "developer" {
							cooperationCompanyItem.ContactCnt = cnt.PurchaseContactCnt
						} else {
							cooperationCompanyItem.ContactCnt = cnt.SupplierContactCnt
						}

					}
				}
				//cooperationCompanyItem.ContactCnt = int32(len(contactList))

				if cooperationCompanyTotal >= startNum {
					cooperationCompany.CooperationCompany = append(cooperationCompany.CooperationCompany, cooperationCompanyItem)
				}
				cooperationCompanyTotal += 1

			}
		}

		cooperationCompanyMap, err := simplecopier.StructToMapByJsonTag(cooperationCompany)
		if err != nil {
			stark.Logger.Error(ctx, "struct to map,err:", err)
		}
		res["list"] = cooperationCompanyMap["cooperation_company"]
		res["total"] = len(cooperationCompany.CooperationCompany)
		return res
	}
}
func (s *ContactService) getCompanyTargetCnt(ctx *gin.Context, companyName []string) []*bigdata.GetCompanyTargetItem {
	if len(companyName) <= 0 {
		return make([]*bigdata.GetCompanyTargetItem, 0)
	}
	bigdataRequest := &bigdata.GetCompanyTargetRequest{
		CompanyName: companyName,
	}
	getCompanyContactCntResponse, err := s.bigDataServiceRepo.GetCompanyTarget(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata GetCompanyTarget,err:%s", err.Error())
	}
	return getCompanyContactCntResponse.List
}
func (s *ContactService) distinctName(ctx *gin.Context, companyList []*pb.CompanyList) []*pb.CompanyList {
	newCompanyList := make([]*pb.CompanyList, 0)
	nameSet := make([]string, 0)
	for _, value := range companyList {
		item := &pb.CompanyList{}
		item.CompanyName = value.CompanyName
		item.OrganizingCode = value.OrganizingCode
		isContain := false
		for _, p := range nameSet {
			if p == value.CompanyName {
				isContain = true
			}
		}
		if !isContain {
			newCompanyList = append(newCompanyList, item)
		}
		nameSet = append(nameSet, value.CompanyName)
	}
	return newCompanyList
}

func (s *ContactService) GetContactList(ctx *gin.Context, request *dto.ContactListRequest) (map[string]interface{}, error) {
	//1、构建请求参数
	requestPb := &pb.ContactListRequest{
		ContactType:          request.ContactType,
		Keyword:              request.Keyword,
		ProvinceCode:         request.ProvinceCode,
		CityCode:             request.CityCode,
		PhoneType:            strings.Join(request.PhoneType, ","),
		PurchaseOwnerMobile:  request.PurchaseOwnerMobile,
		PageSize:             request.PageSize,
		Page:                 request.Page,
		CooperationTimeStart: request.CooperationTimeStart,
		CooperationTimeEnd:   request.CooperationTimeEnd,
		AreaCode:             strings.Join(request.AreaCode, ","),
		JobType:              strings.Join(request.JobType, ","),
	}
	for _, companyItem := range request.Company {
		requestPb.Company = append(requestPb.Company, &pb.CompanyList{CompanyName: companyItem.CompanyName, OrganizingCode: companyItem.OrganizingCode})
	}

	for _, cooperationCountItem := range request.CooperationCount {
		requestPb.CooperationCount = append(requestPb.CooperationCount, &pb.CooperationCount{Max: cooperationCountItem.Max, Min: cooperationCountItem.Min})
	}

	data, err := s.contactRepo.GetContactList(ctx, requestPb)
	if data == nil {
		return map[string]interface{}{
			"total": 0,
			"list":  make([]string, 0),
		}, nil
	}
	if len(request.Company) == 4 { //中标特殊处理
		return s.getWinBidContact(ctx, requestPb, data), nil
	}

	developerCount := 0
	if request.ContactType == "developer_and_supplier" && (request.Company[0].CompanyName != "" || request.Company[0].OrganizingCode != "") { //“全部” = 开发商+供应商
		developerCount += 1
		developerCompany := &pb.CooperationCompanyList{
			ContactCnt:                data.ContactTotal,
			CooperationCompanyName:    request.Company[0].CompanyName,
			CooperationOrganizingCode: request.Company[0].OrganizingCode,
			Contact:                   data.ContactList,
			CompanyType:               "developer",
		}
		if len(developerCompany.Contact) > 2 {
			developerCompany.Contact = developerCompany.Contact[0:2]
		}

		newCooperationCompany := make([]*pb.CooperationCompanyList, 0)
		newCooperationCompany = append(newCooperationCompany, developerCompany)
		for _, value := range data.CooperationCompany {
			newCooperationCompany = append(newCooperationCompany, value)
		}

		data.CooperationCompany = newCooperationCompany
	}

	res := map[string]interface{}{}
	dataMap, err := simplecopier.StructToMapByJsonTag(data)
	if err != nil {
		stark.Logger.Error(ctx, "struct to map,err:", err)
	}

	switch request.ContactType {
	case "single_developer":
		res["list"] = dataMap["contact_list"]
		res["total"] = data.ContactTotal
		break
	case "single_supplier":
		res["list"] = dataMap["contact_list"]
		res["total"] = data.ContactTotal
		break
	case "single_customer":
		res["list"] = dataMap["contact_list"]
		res["total"] = data.ContactTotal
		break
	case "multi_supplier":
		res["list"] = dataMap["cooperation_company"]
		res["total"] = data.CooperationCompanyTotal
		break
	case "developer_and_supplier":
		res["list"] = dataMap["cooperation_company"]
		res["total"] = data.CooperationCompanyTotal + (int32(developerCount))
		break
	default:
		break
	}

	if err != nil {
		return map[string]interface{}{
			"total": 0,
			"list":  make([]string, 0),
		}, err
	}
	return res, nil
}

func (s *ContactService) ContactDetail(ctx *gin.Context, request *pb.ContactDetailRequest) (map[string]interface{}, error) {
	contactResp, err := s.contactRepo.ContactDetail(ctx, request)
	if err != nil {
		stark.Logger.Error(ctx, "获取联系人详情，失败:", err)
		return nil, err
	}
	if len(contactResp.List) < 1 {
		return nil, nil
	}
	resp, err := simplecopier.StructToMapByJsonTag(contactResp.List[0])
	if err != nil {
		stark.Logger.Error(ctx, "struct to map，失败:", err)
	}
	return resp, nil
}

// 合作案例
func (s *ContactService) CooperationList(ctx *gin.Context, request *pb.CooperationListRequest) (map[string]interface{}, error) {
	contactResp, err := s.contactRepo.CooperationList(ctx, request)
	if err != nil {
		stark.Logger.Error(ctx, "获取合作案例，失败:", err)
	}
	if contactResp.Total < 1 {
		return nil, nil
	}
	resp, err := simplecopier.StructToMapByJsonTag(contactResp)
	if err != nil {
		stark.Logger.Error(ctx, "struct to map，失败:", err)
	}
	return resp, nil
}

func (s *ContactService) GetMobile(ctx *gin.Context, request *pb.GetMobileRequest) (map[string]interface{}, error) {
	contactResp, err := s.contactRepo.GetMobile(ctx, request)
	if err != nil {
		stark.Logger.Error(ctx, "获取手机号，失败:", err)
	}
	resp, err := simplecopier.StructToMapByJsonTag(contactResp)
	if err != nil {
		stark.Logger.Error(ctx, "struct to map，失败:", err)
	}
	return resp, nil
}
